package com.liuxing.doctor.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.liuxing.doctor.common.Object.ReturnObject;
import com.liuxing.doctor.common.util.DateUtils;
import com.liuxing.doctor.dto.InspectionDto;
import com.liuxing.doctor.entity.Doctor;
import com.liuxing.doctor.entity.Inspection;
import com.liuxing.doctor.entity.InspectionItem;
import com.liuxing.doctor.entity.Patient;
import com.liuxing.doctor.service.DepartmentService;
import com.liuxing.doctor.service.InspectionItemService;
import com.liuxing.doctor.service.InspectionService;
import com.liuxing.doctor.service.PatientService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 行柳
 * 学习使用
 */
@Slf4j
@Controller
@RequestMapping("/applicationForm")
public class ApplicationFormController {
    @Resource
    private PatientService patientService;
    @Resource
    private InspectionService inspectionService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private InspectionItemService inspectionItemService;
    /**
     * 跳转申请单
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/index")
    public String index(Model model, HttpServletRequest request){
        Doctor doctor= (Doctor) request.getSession().getAttribute("doctor");
        model.addAttribute("doctor",doctor);
        return "main/applicationForm";
    }

    /**
     * 回显病人申请单信息
     * @param patient_id
     * @return
     */
    @RequestMapping("/inspectionInformation")
    @ResponseBody
    public Object inspectionInformation(String patient_id){
        Map<String,Object> resMap=new HashMap<>();
        Patient patient=patientService.queryById(patient_id);
        resMap.put("patient",patient);
        List<Inspection> inspections=inspectionService.queryByPatientId(patient_id);
        if(patient.getMedicalRecordId()!=0){
            if(inspections.size()!=0){
                List<InspectionDto> inspectionDtos=new ArrayList<>();
                for (Inspection i:inspections
                ) {
                    InspectionDto inspectionDto=new InspectionDto();
                    //将检查的信息放进dto
                    inspectionDto.setInspection(i);
                    //讲执行科室放进dto
                    inspectionDto.setExecutiveDivision(departmentService.queryDepartmentById(i.getExecutiveDivision()).getDepartmentName());
                    //将检查名称放进dto
                    inspectionDto.setInspectionItemName(inspectionItemService.queryByExecutiveDivision(i.getExecutiveDivision()).getInspectionItemName());
                    inspectionDtos.add(inspectionDto);
                }
                //获取任意一个Inspection来获取不变的 检查单基本信息
                Inspection inspection_info=inspections.get(0);
                //获得最新的申请单时间
                Date latest_application_time=inspections.stream().sorted((x, y)->
                        DateUtils.formateDateTime(y.getApplyDate()).compareTo(DateUtils.formateDateTime(x.getApplyDate()))
                ).collect(Collectors.toList()).get(0).getApplyDate();
                resMap.put("inspection_info",inspection_info);
                resMap.put("latest_application_time",DateUtils.formateDate(latest_application_time));
                resMap.put("inspectionDtos",inspectionDtos);
                return resMap;
            }
            resMap.put("code","0");
            resMap.put("msg","该病人还没有检查单，请新建");
            return resMap;
        }
        resMap.put("code","0");
        resMap.put("msg","该病人还为诊断病历，请先诊断");
        return resMap;

    }

    /**
     * 查询所有检查条目
     * @return
     */
    @RequestMapping("/inspectionItemList")
    @ResponseBody
    public Object inspectionItemList(){
        List<InspectionItem> inspectionItems=inspectionItemService.queryAll();
        Map<String,Object> resMap=new HashMap<>();
        resMap.put("inspectionItems",inspectionItems);
        return resMap;
    }

    /**
     * 根据id查询单条检查条目
     * @param inspectionItemId
     * @return
     */
    @RequestMapping("/queryOneInspectionItem")
    @ResponseBody
    public Object  queryOneInspectionItem(String inspectionItemId){
        InspectionItem inspectionItem=inspectionItemService.queryByInspectionItemId(inspectionItemId);
        String departmentName=departmentService.queryDepartmentById(inspectionItem.getExecutiveDivision()).getDepartmentName();
        Map<String,Object> resMap=new HashMap<>();
        resMap.put("departmentName",departmentName);
        return resMap;
    }

    /**
     * 新建检查项目或者更新信息
     * @param description
     * @param medicalHistory
     * @param attention
     * @param applyDate
     * @param inspection_array
     * @param patient_id
     * @return
     */
    @RequestMapping("/saveOrUpdateInspectionApplicationForm")
    @ResponseBody
    public Object saveOrUpdateInspectionApplicationForm(
            String description,String medicalHistory,String attention,String applyDate,String inspection_array,String patient_id
    ){
        //结果集
        Map<String,Object> resMap=new HashMap<>();
        Patient patient=patientService.queryById(patient_id);
        if(patient.getMedicalRecordId()==0){
            resMap.put("message","该病人还未诊断病历，请先诊断");
            return resMap;
        }
        //前端传到后端检查项目目的二维数组信息,根据每组的第一个数据判断数据库是否存在该检查项目，来决定新建还是更新
        /*[["50001","CT","脑科","脑部","立即使用","1"],["50002","核磁共振","核磁共振","脑部","次日使用","1"]]*/
        JSONArray jsonArrays=JSON.parseArray(inspection_array);
        //前端传过来的检查项目数量
        int InspectionProjectSize=jsonArrays.size();
        //传参集
        Map<String,Object> map=new HashMap<>();
        map.put("applyDate",DateUtils.formateDateTime(DateUtils.parseDate(applyDate)));
        map.put("description",description);
        map.put("medicalHistory",medicalHistory);
        map.put("attention",attention);
        int resCode=0;
        List<Integer> inspectionIds=new ArrayList<>();
        for(int i=0;i<InspectionProjectSize;i++){
            JSONArray singleJsonArray=JSON.parseArray(jsonArrays.get(i).toString());
            String inspectionId=singleJsonArray.getString(0);
            Inspection inspection=inspectionService.queryByInspectionId(inspectionId);
            if(inspection==null){
                //新建一条检查项目
                //得到检查条目的基本信息
                InspectionItem inspectionItem=inspectionItemService.queryByInspectionItemName(singleJsonArray.getString(1));
                map.put("inspectionItemId",inspectionItem.getInspectionItemId());
                map.put("executiveDivision",inspectionItem.getExecutiveDivision());
                map.put("frequency",singleJsonArray.getString(4));
                map.put("quantity",singleJsonArray.getString(5));
                map.put("sample",singleJsonArray.getString(3));
                map.put("patient_id",patient_id);
                resCode+=inspectionService.createOneInspectionProject(map);
                inspectionIds.add(inspectionService.queryLastInsertId());
            } else{
                //该检查项目已存在，更新其他信息
                map.put("inspectionId",inspectionId);
                resCode+=inspectionService.updateOneInspectionProjectById(map);
            }
        }
        if(resCode>0){
            resMap.put("code","1");
            resMap.put("message","保存成功");
            resMap.put("inspectionIds",inspectionIds);
            return resMap;
        }
        resMap.put("message","网络连接错误，请稍后再试");
        return resMap;
    }
    @RequestMapping("/print")
    @ResponseBody
    public Object print(String inspection_id){
        ReturnObject returnObject=new ReturnObject();
        Inspection inspection=inspectionService.queryByInspectionId(inspection_id);
        if(inspection==null){
            returnObject.setCode("0");
            returnObject.setMessage("该条目为保存，请保存后打印");
            return returnObject;
        }
        return returnObject;
    }
    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(String inspection_id){
        ReturnObject returnObject=new ReturnObject();
        int resCode=inspectionService.deleteOneInspectionProjectById(inspection_id);
        if(resCode>0){
            returnObject.setCode("1");
            return returnObject;
        }
        returnObject.setMessage("网络连接错误，请稍后再试");
        return returnObject;
    }
}
